﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Components;
using UI.Lib;

namespace UI.BuyManagement
{
    public partial class FrmBuy3a00Medit : UI.ParentForm.BaseMedit
    {
        private bool isReadOnly = false;

        public FrmBuy3a00Medit(string modulecode, string action, string text, string key)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.Text = text;
            this.Key = key;

            //回写的方法
            this.SaveCallFuntion = "Buy3a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            this.allowDtlEmpty = false; //可能用户一次想把全部的记录删除
            this.MaxStateFlag = true;//打开页面后让窗口最大化
            if (!string.IsNullOrEmpty(this.Key))
            {
                LoadData();
                IsAfterSaveCloseWin = true;
            }
            if ("P" == action)
            {
                tspBtnAdd.Visible = false;
                tspBtnDel.Visible = false;
                this.saveDtlDataToServer = false;
                this.tspSave.Text = "审 核";
            }
        }

        protected override void PageInit()
        {
            this.tbSummary.DefaultWidth = 130;
        }

        protected override bool BeforeDtlPopUp(string name, ref string where, ref string[] others)
        {
            if ("productcode" == name)
            {
                where = string.Format("status = '1' {0}", Context.GetAppKeyWhere("a.muser", true));

                string table = string.Format(@"Pot3a00_view a
LEFT JOIN Bas0a05 b ON a.taxid = b.listid
LEFT JOIN Sto6a00 e ON a.listid = e.pid AND e.storageid = '{0}'",
                Validation.ToString(this.tbSummary.GetValue("slistid")));

                others = new string[] { table };
            }

            return true;
        }

        //新增行后触发，用户只读概要
        protected override void AfterAddRow()
        {
            if (isReadOnly == true) return;

            this.tbSummary.Enable("stocode", false);
            this.tbSummary.Enable("taxcode", false);
        }

        protected override void AfterSaveData(bool isSuccess)
        {
            if (isSuccess)
            {
                this.tbSummary.Enable("stocode", true);
                this.tbSummary.Enable("taxcode", true);
                isReadOnly = false;
            }
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            if ("providercode" == name) //对销售商进行公司限制
            {
                where = string.Format(" status <> '4' {0} ", Context.GetAppKeyWhere("usercode", true));
            }
            else if ("stocode" == name) //仓库信息
            {
                where = string.Format("statuscode = '1' {0}",
                    Context.GetAppKeyWhere("usercode", true));
            }
            else if ("taxcode" == name)
            {
                where = Context.GetAppKeyWhere("muser");
            }

            return true;
        }

        protected override void AfterCreateSummaryControl(string name, Control c)
        {
            if ("ordate" == name) //给日期控件添加一个事件
            {
                DateTimePicker dp = c as DateTimePicker;
                dp.ValueChanged += new EventHandler(dp_ValueChanged);
            }
            else if ("pdate" == name || "providercode" == name)
            {
                TextBox dp = c as TextBox;
                dp.TextChanged += new EventHandler(dp_ValueChanged);
            }
        }

        void dp_ValueChanged(object sender, EventArgs e)
        {
            //计算应收货日期
            int pdate = Validation.ToInt(this.tbSummary.GetValue("pdate"));
            DateTime ordate = Convert.ToDateTime(this.tbSummary.GetValue("ordate"));
            this.tbSummary.SetValue("backdate", ordate.AddDays(pdate).ToShortDateString());
        }

        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.listid ='{0}' ", this.Key));
            base.LoadDtlData(null, string.Format(" a.plistid ='{0}' ", this.Key));
        }

        protected override void AfterGridEndEdit(string colName, DataGridViewCellEventArgs e)
        {
            if ("ordqty" == colName || "price" == colName) //修改完订货数量，计算总额
            {
                double price = Validation.ToDouble(this.dgvDtl.GetValue("price")); //价格
                double ordqty = Validation.ToDouble(this.dgvDtl.GetValue("ordqty")); //订货数量
                double all = price * ordqty; //还要算上税率

                this.dgvDtl.SetValue("ordamt", all + all * Validation.ToDouble(this.dgvDtl.GetValue("cess")));
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("ordamt" == name) //订单总额变化后更新概要的订单总额
            {
                this.tbSummary.SetValue("ordamt", CalcDtlAmt());

                //计算税额
                double pct = Validation.ToDouble(this.dgvDtl.GetValue("cess"));
                double ordamt = Validation.ToDouble(this.dgvDtl.GetValue("ordamt"));

                this.dgvDtl.SetValue("cessamt", Validation.ToDouble(pct * ordamt, 3));
            }
            else if ("ordqty" == name)
            {
                double bordqty = Validation.ToDouble(this.dgvDtl.GetValue("bordqty"));
                double now = Validation.ToDouble(value);
                if (bordqty == 0 || 0 == now) return;

                //订货数及赠品数按收到的订单手工输入，订货量不是起订量的倍数提示用户；				
                if (now % bordqty != 0)
                {
                    if (MessageBox.Show("订货数量不是起订数量的整数倍，是否确认?", "提示", MessageBoxButtons.YesNo) ==
                         DialogResult.No)
                    {
                        this.dgvDtl.SetValue("ordqty", "0");
                    }
                }
            }
        }

        private double CalcDtlAmt()
        {
            double sum = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sum += Validation.ToDouble(dr.Cells["ordamt"].Value);
            }

            return sum;
        }

        protected override void AfterDelete()
        {
            if (this.dgvDtl.Rows.Count == 0)
            {
                this.tbSummary.Enable("stocode", true);
                this.tbSummary.Enable("taxcode", true);
                isReadOnly = false;
            }

            this.tbSummary.SetValue("ordamt", CalcDtlAmt());
        }

        protected override bool Check()
        {
            if ("P" == this.Action)
            {
                double gainpct = Validation.ToDouble(this.tbSummary.GetValue("gainpct"));
                if (gainpct < 0)
                {
                    return (MessageBox.Show("毛利率为负数，是否继续？", "提示", MessageBoxButtons.OKCancel)
                        == DialogResult.OK);
                }
            }

            return true;
        }
    }
}
